package com.mht2017.common.dto;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.mht2017.common.utils.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;


/**
 * 固定大小的Map<br/>
 * 多余的key将会在put的时候被移除
 *
 * @author yutong.xiao
 * @date 2017年10月25日 下午12:58:43
 */
public class FixedSizeMap {

	private int fixSize;
	private Map<Number, Number> map = new LinkedHashMap<>();

	public FixedSizeMap(int fixSize) {
		this.fixSize = fixSize;
	}

	public synchronized Number getAndRemove(Object key) {
		return map.remove(key);
	}

	public Number put(Number key, Number value) {
		Number put = map.put(key, value);
		checkSize();
		return put;
	}

	private void checkSize() {
		if (null != map) {
			int delta = map.size() - fixSize;
			if (delta == 1) {
				synchronized (map) {
					map.remove(CollectionUtil.getFirst(map.keySet()));
				}
			} else if (delta > 1) {
				List<Number> toRemoveList = CollectionUtil.getBefore(map.keySet(), delta);
				if (CollectionUtils.isNotEmpty(toRemoveList)) {
					synchronized (map) {
						for (Number number : toRemoveList) {
							map.remove(number);
						}
					}
				}
			}
		}
	}

}
